# -*- coding: utf-8 -*-
"""
Created on Thu May 13 10:20:22 2021

@author: Hu Yue
@email: hhhuyue@gmail.com

Note:
"""

import pandas as pd
from hedge_utils import get_hedged_retDT1,get_bt_delta
from datetime import datetime
import numpy as np

import warnings
warnings.filterwarnings("ignore")

# load data
option_trade = pd.read_csv("domestic data/options_trade_all.csv",usecols=['date','contract_code','close','iv','delta','vega','gamma','theta','vol','rho'])
option_trade['date'] = pd.to_datetime(option_trade['date'],format="%Y-%m-%d")

future_trade = pd.read_csv("domestic data/futures_trade_all.csv",usecols=['date','code','close','va_type'])
future_trade['date'] = future_trade['date'].apply(lambda x: pd.to_datetime(x,format="%Y-%m-%d"))

# load data of informations
option_info = pd.read_csv("domestic data/options_info_all.csv",usecols=['contract_code','object_code','strike_price','strike_way','final_date'])
option_info = option_info.drop_duplicates(subset = ['contract_code'])
option_info.loc[:,'cp_type'] = option_info['contract_code'].apply(lambda x: (-1)**((x.split("-")[1]=='P')*1))
option_info['final_date'] = pd.to_datetime(option_info['final_date'],format='%Y%m%d')



# data preprocessing
option_trade_info = pd.merge(option_trade,option_info,how='left',on='contract_code')
#option_trade_info.loc[:,'time2mat'] = (pd.eval('option_trade_info.final_date - option_trade_info.date'))#.dt.days

option_trade_info.loc[:,'time2mat'] = ((option_trade_info.final_date - option_trade_info.date).dt.days)
#%%
# 提取豆粕和玉米的数据

future_trade = future_trade[future_trade['va_type'].str[0:2]!="生猪"]

# 修改变量名字
future_trade.rename(columns={'close':'future_price'},inplace=True)
option_trade_info.rename(columns={'close':'option_price','object_code':'code'},inplace=True)

#%% 单个期权hedge的测试

#start_date = datetime.strptime('2017-03-31', '%Y-%m-%d')
#end_date = datetime.strptime('2017-06-07', '%Y-%m-%d')
# =============================================================================
# start_date = pd.to_datetime('2017-03-31',format="%Y-%m-%d")
# end_date = pd.to_datetime('2018-02-07',format="%Y-%m-%d")
# contract_code = 'm1803-P-2750'#'m1707-P-2900'
# code = 'm1803'
# 
# params = {'start_date':start_date,
#           'end_date':end_date,
#           'contract_code':contract_code,
#           'code':code}
# future_info = future_trade[future_trade['code']==code]
# future_info = future_info[(future_trade['date']>=start_date)&(future_trade['date']<=end_date)]
# 
# option_info = option_trade_info[option_trade_info['contract_code']==contract_code]
# option_info = option_info[(option_info['date']>=start_date)&(option_info['date']<=end_date)]
# 
# filepath = "{}.json".format(contract_code)
# 
# ret,hedge_info = get_hedged_retDT1(future_info,option_info,params,filepath)
# =============================================================================

#%%
# 说明天软算出来的真的没啥问题
# =============================================================================
# from hedge_utils import get_bt_delta
# # 自己算一遍美式的delta瞅瞅呢
# temp  = hedge_info[['date','future_price','strike_price','time2mat','iv','delta','cp_type']]
# 
# for idx,option in temp.iterrows():
#     
#     temp.loc[idx,'adjst_Delta'] = get_bt_delta(option['future_price'],option['strike_price'],option['time2mat']/365,option['iv']/100,option['cp_type'])
#     print(option['future_price'],option['strike_price'],option['time2mat']/365,option['iv']/100,option['cp_type'])
# # =============================================================================
import os
code_1 = pd.DataFrame(future_trade['code'][~(future_trade['code'].duplicated())])
code_2 = pd.DataFrame(option_trade_info['code'][~(option_trade_info['code'].duplicated())])
#%%
codes = code_2.merge(code_1,on='code',how='inner')['code'].values
#%%
for code in codes:
    
    future_info = future_trade[future_trade['code']==code]
    option_info = option_trade_info[option_trade_info['code']==code]
    print("hello?")
    file_path = "result_agri/{}/".format(code)
    if not os.path.exists(file_path):
        os.makedirs(file_path)
        
    days = option_info['time2mat'][~(option_info['time2mat'].duplicated())]
    days = days[days>=7]
    
    for day in days:
        
        file_name ="{}_{}.json".format(code,day)
        option_info_ = option_info[option_info['time2mat']==day]   # 筛选剩余到期时间相同的期权
        dates = option_info_[['date','final_date']][~(option_info_['date'].duplicated())]
        for _,dat in dates.iterrows():
            
            start_date = pd.to_datetime(dat['date'])
            end_date = pd.to_datetime(dat['final_date'])
            future_info_ = future_info[(future_info['date']<=end_date)&(future_info['date']>=start_date)] # 筛选出同个到期日的期权
            #
            #print(future_info_)
            option_info_e = option_info[(option_info['date']<=end_date)&(option_info['date']>=start_date)]
            
            print("the date is {}".format(start_date))
            for idx,row in option_info_.iterrows():
                option = row['contract_code']
                print("the option is {}".format(option))
                option_info_s = option_info_e[option_info_e['contract_code']==option]
                
                params = {'start_date':start_date,
                          'end_date':end_date,
                          'contract_code':option,
                          'code':code}
                filepath = file_path+file_name
                ret,hedge_info = get_hedged_retDT1(future_info_,option_info_s,params,filepath)
                #print(hedge_info)
    
#%%

# 读取m1803_92的数据
# =============================================================================
# import jsonlines
# import pandas as pd
# data = []
# code ='m1803'  # 106544
# time2mat = 30
# with open('result_agri/{}/{}_{}.json'.format(code,code,time2mat),'r') as f:
#     for item in jsonlines.Reader(f):
#         data.append(item)
#     
# 
# data = pd.DataFrame(data)
# =============================================================================


#%%

# =============================================================================
# data.loc[:,'moneyness'] = data['startprice'] / data['K']
# data1 = data[((data['moneyness'])>=0.95)&((data['moneyness'])<=1.05)]
# data1 = data1[data1['VOL']>0]
# =============================================================================

